import { invokeAsyncAPi } from '@/xz-fn.js'
import { getRights, getMemberInfo, getUserToken, getMonthTokenDrawStatus } from '@/api/common'
import { parseTime } from '@/utils'
let pkg_id = process.env.VUE_APP_PACKAGE_ID
let pkgForAI = ({
  'xz': ['10012', '10013', '10014', '10015'],
  'dll': ['80512', '80513', '80514', '80515']
})[process.env.VUE_APP_NAME]

const state = {
  token: '',
  hasLogin: false,
  userInfo: {
    userRights: [],
    userToken: 0,
    userid: '',
    userTokenList: [],
    canDrawToken: false// 是否可以手动领取token，yueshu里面是手动领取，xz是自动领取
  }
}

const mutations = {
  SET_TOKEN (state, token) {
    state.token = token
  },
  SET_HASLOGIN (state, val) {
    state.hasLogin = val
  },
  SET_USERINFO (state, param) {
    Object.keys(param).forEach(key => {
      state.userInfo[key] = param[key]
    })
  },
  RESET_USERINFO (state, param) {
    state.userInfo = Object.assign({}, param)
  }
}

const actions = {
  resetUserInfo ({ commit }) {
    commit('RESET_USERINFO', { userRights: [], userToken: 0, userTokenList: [], userid: '' })
    commit('SET_HASLOGIN', false)
    commit('SET_TOKEN', '')
  },
  /**
   * 获取用户基础信息
   */
  getUserInfo ({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      // 本地调用
      // const user = {
      //   'Logon': true,
      //   'Token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHAiOjAsImF1dGhvcml6ZV9pZCI6MTMwNTg2MDcsImRhdGFzY29wZSI6ImJhc2UiLCJleHAiOjE3NDM0MDUzMzUsImlkZW50aXR5IjoxMzAwMjI1NiwibmljZSI6IjEzNSoqKioyMjIiLCJvcmlnX2lhdCI6MTc0MjU0MTMzNSwicmVmcmVzaCI6MzI5NjAwMDAwMDAwMDAwMCwidGlkIjo5MDk0NzUyNzUxNTcxNzYzMjAsInR5cGUiOjJ9.tkxxn1p4Ko8uYUfP-n3CS_T64NPiD4lcjfkrUShrV9U',
      //   'UserHead': '',
      //   'UserID': '13002321'
      // }
      // commit('SET_USERINFO', user)
      // commit('SET_HASLOGIN', !!user.userid || !!user.UserID)
      // commit('SET_TOKEN', user.token || user.Token)
      // resolve()

      const name = process.env.VUE_APP_XZ_GET_USER_INFO
      invokeAsyncAPi(name).then(res => {
        const user = Array.isArray(res) ? res[0] : res
        // if (user) {
        // user.userid = user.userid || user.UserID || ''
        // commit('SET_USERINFO', user)
        let token = ''
        if (typeof user === 'string') { // dll里面，这里是token
          token = user
        } else { // 其他项目，这里是一个对象
          token = user?.token || user?.Token
        }
        commit('SET_USERINFO', { userid: user?.UserID || '' })
        commit('SET_HASLOGIN', !!token)
        commit('SET_TOKEN', token)
        resolve()
        // } else {
        //   reject(user)
        // }
      }).catch(e => {
        reject(e)
      })
    })
  },
  /**
   * 获取权益信息
   */
  // eslint-disable-next-line sonarjs/cognitive-complexity
  async getUserRights ({ commit, dispatch, rootState, state }, isShowDynamic = false) {
    if (rootState.system.info.appID === 111) {
      pkgForAI = ['20018', '20019', '20022', '20023']
      pkg_id = '20000'
    }
    if (process.env.VUE_APP_BUY_TYPE === 'right') {
      const { data } = await getRights({ pkg_id })
      const userRights = (data?.data?.rights || []).filter((item) => pkgForAI.includes(item.right_id))
      commit('SET_USERINFO', { userRights: userRights || [] })
      return
    }

    if (!state.hasLogin) {
      commit('SET_USERINFO', { userToken: 0, userTokenList: [] })
      return
    }

    const { data } = await getUserToken()
    if (data?.code === 200) {
      const list = data.data?.list || []
      let group = []

      if (process.env.VUE_APP_BUY_TYPE === 'energy') {
        group = [{
          type: 'given',
          name: '平台能量赠送',
          list: []
        }, {
          type: 'bought',
          name: '加购能量包',
          list: []
        }]
        list.forEach(it => {
          const { amount, valid_time: time, unlimit, cat } = it
          const unlimited = !!unlimit
          const valid_time = unlimited ? '' : parseTime(time * 1000)
          const list = cat === 'order' ? group[1].list : group[0].list
          const sort = new Date(valid_time)?.getTime()
          list.push({
            amount,
            valid_time,
            unlimited,
            sort
          })
        })
        group.forEach(({ list }) => {
          if (!list.length) {
            list.push({
              amount: 0
            })
          } else {
            // 接口返回排序是按有效期最久在前
            list.sort((a, b) => {
              if (b.unlimited) return -1
              return a.sort - b.sort
            }) // 快到期在前
          }
        })
      }
      if (isShowDynamic) {
        const count = state.userInfo.userToken - data.data.count
        // eslint-disable-next-line max-depth
        if (count > 1) {
          dispatch('chat/setDynamicToken', count, { root: true })
        }
      }
      commit('SET_USERINFO', { userToken: data.data.count, userTokenList: group })
    }
  },
  /**
   * 获取权益信息
   */
  async getMemberInfos ({ commit, dispatch, rootState }) {
    if (process.env.VUE_APP_BUY_TYPE === 'token') {
      const { data } = await getMonthTokenDrawStatus()
      if (data?.code === 200) {
        commit('SET_USERINFO', { canDrawToken: !!data?.data?.can_join })
      }
    }
    if (rootState.system.info.appID === 111) {
      pkg_id = '20000'
    }
    const { data } = await getMemberInfo()
    if (data?.code === 200) {
      const packages = data?.data?.buy_right_package?.filter((v) => v.pkg_id === pkg_id) || []
      const isvip = packages.some((item) =>
        item.unlimited || new Date(item.expire_at).getTime() / 1000 > parseInt(data?.data?.server_time || '')
      )
      commit('SET_USERINFO', { is_member: isvip })
      return
    }
    commit('SET_USERINFO', { is_member: false })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
